package org.ben.cyclicbarrier;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTester {
    public static void main(String[] args) {
        AltWorker altW = new AltWorker();
        CyclicBarrier cb = new CyclicBarrier(5,altW);
        for(int i = 0; i < 5; i++) {
            Worker w = new Worker(cb);
            Thread altT = new Thread(w);
            altT.start();
        }
    }
}

class Worker implements Runnable {
    CyclicBarrier cb;

    Worker(CyclicBarrier cb) {
        this.cb = cb;
    }

    public void run() {
        try {
            System.out.println(Thread.currentThread().getName() + " Worker...");
            Thread.sleep(1000);
            /* Below block is used to test thread state if exception happens.
             * 
             * if(Thread.currentThread().getName().equals("Thread-4")) {
                System.out.println(Thread.currentThread().getName() + " interrupted...");
                Thread.currentThread().interrupt();
            }
            */
            cb.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}

class AltWorker implements Runnable {

    public void run() {
        System.out.println("AltWorker...");
    }
}
